// 导入db模块
const db = require('../config/db');

// 评论类
class Comment {
    // 发表评论
    add(c_id, c_text, c_create_time, from_user_id, to_user_id, article_id){
        return new Promise((resolve,reject)=>{
            let sql = `insert into db_comment(c_id, c_text, c_create_time, from_user_id, to_user_id, article_id) 
             values('${c_id}','${c_text}','${c_create_time}','${from_user_id}','${to_user_id}','${article_id}')`;

             db.query(sql)
             .then(
                (result)=>{
                    // console.log(result)
                    if(result.affectedRows === 1) {
                        resolve({
                            code: 200,
                            msg: '发表评论成功。'
                        })
                    }
                    else {
                        resolve({
                            code: -1,
                            msg: '发表评论失败。'
                        })
                    }
                    
                },
                (err)=>{
                    reject({
                        code: -1,
                        msg: '发表评论失败。',
                        err 
                    })
                }
             )
        })
    }

    // 删除评论
    remove(c_id,from_user_id){
        return new Promise((resolve,reject)=>{
            let sql = `delete from db_comment where c_id = '${c_id}' and from_user_id = '${from_user_id}'`
            db.query(sql)
            .then(
                (result)=>{
                    // console.log(result);
                    if(result.affectedRows === 1) {
                        resolve({
                            code: 200,
                            msg: '删除评论成功。'
                        })
                    }
                    else {
                        resolve({
                            code: -1,
                            msg: '您不能删除别人的评论。'
                        })
                    }
                   
                },
                (err)=>{
                    reject({
                        code: -1,
                        msg: '删除评论失败。',
                        err 
                    })
                }
            )
        })
    }

    // 获取评论
    list(article_id){
        return new Promise((resolve,reject)=>{
            let sql = `select * from db_comment where article_id='${article_id}'`;
            db.query(sql)
            .then(
                (rows)=>{
                    resolve({
                        code: 200,
                        msg: '获取评论列表成功。',
                        result: rows 
                    })
                },
                (err)=>{
                    reject({
                        code: -1,
                        msg: '获取评论列表失败。',
                        err
                    })
                }
            )
        })
    }
}

module.exports = new Comment();